package com.fofia.iotweb.framework.core;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.fofia.iotweb.common.SecureHelper;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class RequestHelper {
    /**
     * 定义移动端请求的所有可能类型
     */
    private final String[] agent = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
    private static final String IP_UTILS_FLAG = ",";
    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
    private static final String LOCALHOST_IP1 = "127.0.0.1";



    public Context getCurrent(){
        // long threadId = Thread.currentThread().getId();
        // System.out.println("已存在Context对象，线程id:"+threadId);
        return Context.current();
    }
    /**
     *
     * @author yushuo
     * @description //获取请求参数 String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String getString(String key,String defaultValue){
        Context solonConext= getCurrent() ;
        String param= solonConext.param(key);
        if(!StrUtil.isEmpty(param)){
            return param.trim();
        }
        return defaultValue.trim();
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 Integer
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public Integer getInt(String key,Integer defaultValue){
        Context solonContext= getCurrent() ;
        String param= solonContext.param(key);
        if(!StrUtil.isEmpty(param)){
            return Convert.toInt(param.trim(),defaultValue);
        }
        return defaultValue;
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 Long
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public Long getInt64(String key,Long defaultValue){
        Context solonContext= getCurrent() ;
        String param= solonContext.param(key);
        if(!StrUtil.isEmpty(param)){
            return Convert.toLong(param.trim(),defaultValue);
        }
        return defaultValue;
    }

    /**
     *
     * @author yushuo
     * @description //获取请求参数 String[]
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String[] getStringArray(String key){
        Context solonContext= getCurrent() ;
        String[] param=solonContext.paramValues(key);
        if(param==null||param.length==0){
            return new String[]{};
        }
        return param;
    }

    /**
     *
     * @author yushuo
     * @description //获取Header String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String getHeader(String key,String defaultValue){
        Context solonContext= getCurrent() ;
        String headerValue= solonContext.header(key);
        if(!StrUtil.isEmpty(headerValue)){
            return headerValue.trim();
        }
        return defaultValue.trim();
    }

    /**
     * 是否是Ajax异步请求
     *
     * @param
     */
    public boolean isAjaxRequest() {
        Context solonContext= getCurrent() ;
        String accept = solonContext.header("accept");
        if (accept != null && accept.indexOf("application/json") != -1) {
            return true;
        }

        String xRequestedWith = solonContext.header("X-Requested-With");
        if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) {
            return true;
        }

        String uri = solonContext.path();
        if (StrUtil.containsAnyIgnoreCase(uri, ".json", ".xml")) {
            return true;
        }

        String ajax = solonContext.param("__ajax");
        if (StrUtil.containsAnyIgnoreCase(ajax, "json", "xml")) {
            return true;
        }
        return false;
    }

    /**
     * 判断User-Agent 是不是来自于手机
     */
    public boolean isMobile(String ua) {
        boolean flag = false;
        if (!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;"))) {
            // 排除 苹果桌面系统
            if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
                for (String item : agent) {
                    if (ua.contains(item)) {
                        flag = true;
                        break;
                    }
                }
            }
        }
        return flag;
    }

    /**
     *
     * @author 获取用户ip
     * @description //TODO
     * @date 11:31 2021/3/1
     * @param
     * @return java.lang.String
     **/
    public  String getIp(){
        Context solonContext= getCurrent() ;
        String ip = LOCALHOST_IP1;
        try {
            //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
            ip = solonContext.header("X-Original-Forwarded-For");
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = solonContext.header("X-Forwarded-For");
            }
            //获取nginx等代理的ip
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip =solonContext.header("x-forwarded-for");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = solonContext.header("Proxy-Client-IP");
            }
            if (StrUtil.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip =solonContext.header("WL-Proxy-Client-IP");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = solonContext.header("HTTP_CLIENT_IP");
            }
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = solonContext.header("HTTP_X_FORWARDED_FOR");
            }
            //兼容k8s集群获取ip
            if (StrUtil.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = solonContext.realIp();
                if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
                    //根据网卡取本机配置的IP
                    InetAddress iNet = null;
                    try {
                        iNet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        return LOCALHOST_IP1;
                    }
                    ip = iNet.getHostAddress();
                }
            }
        } catch (Exception e) {
            return LOCALHOST_IP1;
        }
        //使用代理，则获取第一个IP地址
        if (!StrUtil.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
            ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
        }

        return ip;
    }


    /**
     *
     * @author yushuo
     * @description //获取Header String
     * @date 9:49 2021/2/2
     * @param [key, defaultValue]
     * @return java.lang.String
     **/
    public String getToken(){
        Context solonContext= getCurrent() ;

        String token= solonContext.header("auth_token");
        if(!StrUtil.isEmpty(token)){
            return token.trim();
        }
        token=solonContext.cookie("auth_token");
        if(!StrUtil.isEmpty(token)){
            return token.trim();
        }
        return "";
    }

    public String getUserName(){
        String token=getToken();
        if(StrUtil.isEmpty(token)){
            return "";
        }

        // String cookie=StrUtil.format("fofia_iot_web;{};{};{}","admin", DateUtil.now(),randomString);
        String tokenInfo= SecureHelper.dencryptDes(token);
        String[] tokenArray=StrUtil.splitToArray(tokenInfo,";");
        return tokenArray[1];
    }

}
